/*
 * Copyright 2002-2022 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.hqd.ch03.v40.web.servlet.support;


import com.hqd.ch03.v40.context.i18n.LocaleContext;
import com.hqd.ch03.v40.context.i18n.TimeZoneAwareLocaleContext;
import com.hqd.ch03.v40.web.servlet.DispatcherServlet;
import com.hqd.ch03.v40.web.servlet.LocaleContextResolver;
import com.hqd.ch03.v40.web.servlet.LocaleResolver;
import com.hqd.ch03.v40.web.servlet.ThemeResolver;

import javax.servlet.http.HttpServletRequest;
import java.util.Locale;
import java.util.Map;
import java.util.TimeZone;

public abstract class RequestContextUtils {

    public static final String REQUEST_DATA_VALUE_PROCESSOR_BEAN_NAME = "requestDataValueProcessor";


    /**
     * Return the {@link LocaleResolver} that has been bound to the request by the
     * {@link DispatcherServlet}.
     *
     * @param request current HTTP request
     * @return the current {@code LocaleResolver}, or {@code null} if not found
     */
    public static LocaleResolver getLocaleResolver(HttpServletRequest request) {
        return (LocaleResolver) request.getAttribute(DispatcherServlet.LOCALE_RESOLVER_ATTRIBUTE);
    }

    public static Locale getLocale(HttpServletRequest request) {
        LocaleResolver localeResolver = getLocaleResolver(request);
        return (localeResolver != null ? localeResolver.resolveLocale(request) : request.getLocale());
    }

    public static TimeZone getTimeZone(HttpServletRequest request) {
        LocaleResolver localeResolver = getLocaleResolver(request);
        if (localeResolver instanceof LocaleContextResolver) {
            LocaleContext localeContext = ((LocaleContextResolver) localeResolver).resolveLocaleContext(request);
            if (localeContext instanceof TimeZoneAwareLocaleContext) {
                return ((TimeZoneAwareLocaleContext) localeContext).getTimeZone();
            }
        }
        return null;
    }

    @SuppressWarnings("unchecked")
    public static Map<String, ?> getInputFlashMap(HttpServletRequest request) {
        return (Map<String, ?>) request.getAttribute(DispatcherServlet.INPUT_FLASH_MAP_ATTRIBUTE);
    }


    public static ThemeResolver getThemeResolver(HttpServletRequest request) {
        return (ThemeResolver) request.getAttribute(DispatcherServlet.THEME_RESOLVER_ATTRIBUTE);
    }

}
